class Solution
{
public:
    long long countSubarrays(vector<int> &nums, int k)
    {
        long long result = 0;
        int n = nums.size();
        int maxNum = *max_element(nums.begin(), nums.end());
        vector<int> maxNumPos;

        for (int i = 0; i < n; i++)
        {
            if (nums[i] == maxNum)
            {
                maxNumPos.push_back(i);
            }
        }

        for (int j = k - 1; j < maxNumPos.size(); ++j)
        {
            int i = j - k + 1;
            long long l = maxNumPos[i] + 1;
            long long r = j < maxNumPos.size() - 1 ? maxNumPos[j + 1] - maxNumPos[j] : n - maxNumPos[j];
            result += l * r;
        }

        return result;
    }
};